package org.jeecg.modules.gzgl.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhaodui.fxy.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gzgl.entity.*;
import org.jeecg.modules.gzgl.service.IFxyGzgl02Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gzgl.service.IFxyGzgl04Service;
import org.jeecg.modules.gzgl.service.impl.FxyGzgl02ServiceImpl;
import org.jeecg.modules.gzgl.service.impl.FxyGzgl03ServiceImpl;
import org.jeecg.modules.system.service.impl.SysDataLogServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 公证相关人员信息
 * @Author: zhaodui
 * @Date:   2020-02-06
 * @Version: V1.0
 */
@RestController
@RequestMapping("/gzgl/fxyGzgl02")
@Slf4j
public class FxyGzgl02Controller extends JeecgController<FxyGzgl02, IFxyGzgl02Service> {
	@Autowired
	private IFxyGzgl02Service fxyGzgl02Service;
	@Autowired
	private RedisUtil redisUtil;
	 @Autowired
	 private SysDataLogServiceImpl sysDataLogService;
	 @Autowired
	 private IFxyGzgl04Service fxyGzgl04Service;
	 @Autowired
	 private FxyGzgl03ServiceImpl fxyGzgl03Service;
	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;
	 @Value(value = "${baseorg.common.appcode}")
	 private String appcode;
	/**
	 * 分页列表查询
	 *
	 * @param fxyGzgl02
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FxyGzgl02 fxyGzgl02,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FxyGzgl02> queryWrapper = QueryGenerator.initQueryWrapper(fxyGzgl02, req.getParameterMap());
		Page<FxyGzgl02> page = new Page<FxyGzgl02>(pageNo, pageSize);
		IPage<FxyGzgl02> pageList = fxyGzgl02Service.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	public String upload(String fileName,String filepath,String filefrom ,String filetype ,String userid){
		String res = "";
					String ctxPath = uploadpath;
		String savePath = uploadpath + File.separator+ filepath;
			try{
 				String appCode = appcode;
 				fxyUser fxyUser = new fxyUser();
				fxyUser.setFileUrl(savePath);
				fxyUser.setUserId(userid);
				fxyUser.setFileName(fileName);
				fxyUser.setFileType(filetype);;
				fxyUser.setFrom(filefrom);

					File filein = new File(savePath);
					res = fxyUtil.uploadFileweb(appCode,redisUtil,fxyUser,filein);
				}catch (BaseBusinessException e){


				}

		return  res;
	}




	/**
	 *   添加
	 *
	 * @param fxyGzgl02
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FxyGzgl02 fxyGzgl02) {

		if(StringUtil.isEmpty(fxyGzgl02.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl02.getQuery39())){//不提交法信
			fxyGzgl02Service.save(fxyGzgl02);
			return Result.ok("添加成功！");
		}
		try{
			String appCode = fxyGzgl02.getQuery01();
			fxyUser fxyUser = new fxyUser();
			fxyUser.setMobile(fxyGzgl02.getQuery12());
			fxyUser.setName(fxyGzgl02.getQuery13());
			fxyUser.setIdType(fxyGzgl02.getQuery14());
			fxyUser.setIdCode(fxyGzgl02.getQuery15());
			fxyUser.setOrgId(fxyGzgl02.getQuery16());
			fxyUser.setEmail(fxyGzgl02.getQuery17());
			fxyUser.setAddress(fxyGzgl02.getQuery18());
			fxyUser.setThirdAccount(fxyGzgl02.getQuery19());
			String res = "";
			if(fxyGzgl02.getQuery27().equals("企业主借人")||fxyGzgl02.getQuery27().equals("企业担保人")){//注册子账号
//				String qyid = fxyGzgl02.getQuery19();
//				String qiyeuserid = "";
//				QueryWrapper<FxyGzgl03> queryWrapper3 = new QueryWrapper<FxyGzgl03>();
//				queryWrapper3.eq("query13", qyid);
//				queryWrapper3.eq("query07", fxyGzgl02.getQuery07());
//				 List<FxyGzgl03> list03 = fxyGzgl03Service.list(queryWrapper3);
//				  qiyeuserid = list03.get(0).getQuery24();
//				  if (StringUtil.isEmpty(qiyeuserid)){
//					  FxyGzgl03 fxyGzgl03 =  list03.get(0);
// 						  try {
// 							  fxyUser fxyUser3 = new fxyUser();
//							  fxyUser3.setEnterpriseName(fxyGzgl03.getQuery12());
//							  fxyUser3.setBusinessLicenseId(fxyGzgl03.getQuery13());
//							  fxyUser3.setOrgId(fxyGzgl03.getQuery14());
//							  fxyUser3.setAddress(fxyGzgl03.getQuery15());
//							  fxyUser3.setLegalPersonType(fxyGzgl03.getQuery16());
//							  fxyUser3.setLegalPersonCard(fxyGzgl03.getQuery17());
//							  fxyUser3.setLegalPersonPhone(fxyGzgl03.getQuery18());
//							  fxyUser3.setEmail(fxyGzgl03.getQuery17());
//							  fxyUser3.setContactsName(fxyGzgl03.getQuery20());
//							  fxyUser3.setContactsPhone(fxyGzgl03.getQuery21());
//							  fxyUser3.setLegalPersonName(fxyGzgl03.getQuery22());
//							  fxyUser3.setLegalPersonMobile(fxyGzgl03.getQuery23());
//							  String res3 = fxyUtil.realnameRegisterEnterpriseUser(appCode, redisUtil, fxyUser3);
//							  if (!StringUtil.isEmpty(res3)) {
//								  fxyGzgl03.setQuery24(res3);
//								  qiyeuserid = res3;
//							  }
//						  } catch (BaseBusinessException e) {
//							  fxyGzgl03.setQuery38(e.getMessage());
//							  fxyGzgl03Service.updateById(fxyGzgl03);
//							  return Result.error(e.getMessage());
//						  }
//					   fxyGzgl03Service.updateById(fxyGzgl03);
//				  }


//				if(StringUtil.isNotEmpty(qiyeuserid)){
//					fxyUser.setUserId(qiyeuserid);
//					res = fxyUtil.registerSubUser(appCode,redisUtil,fxyUser);
//				}else{
//					return Result.ok("企业注册失败");

//				}
			}else{
				res = fxyUtil.realnameRegister(appCode,redisUtil,fxyUser);

			}
//			if(!StringUtil.isEmpty(res)){
//				fxyGzgl02.setQuery20(res);
//				fxyUser.setUserId(res);
//				try{
//					fxyUtil.doRealnameByCA(appCode,redisUtil,fxyUser);
//				}catch (Exception e){
//
//				}
//			}
		}catch (BaseBusinessException e){
			return Result.error(e.getMessage());
		}
		fxyGzgl02.setQuery22("已实名");
		fxyGzgl02Service.save(fxyGzgl02);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl02);
		String id = fxyGzgl02.getId();
		sysDataLogService.addDataLog("fxy_gzgl_02",id,  datacont);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fxyGzgl02
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FxyGzgl02 fxyGzgl02) {
		if(StringUtil.isEmpty(fxyGzgl02.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl02.getQuery39())) {//不提交法信
			fxyGzgl02Service.updateById(fxyGzgl02);
			return Result.ok("编辑成功!");
		}
		String appCode = fxyGzgl02.getQuery01();
		if(StringUtil.isEmpty(fxyGzgl02.getQuery20())){
			try{
			fxyUser fxyUser = new fxyUser();
			fxyUser.setMobile(fxyGzgl02.getQuery12());
			fxyUser.setName(fxyGzgl02.getQuery13());
			fxyUser.setIdType(fxyGzgl02.getQuery14());
			fxyUser.setIdCode(fxyGzgl02.getQuery15());
			fxyUser.setOrgId(fxyGzgl02.getQuery16());
			fxyUser.setEmail(fxyGzgl02.getQuery17());
			fxyUser.setAddress(fxyGzgl02.getQuery18());
			fxyUser.setThirdAccount(fxyGzgl02.getQuery19());
			String res = "";
			if(fxyGzgl02.getQuery27().equals("企业主借人")||fxyGzgl02.getQuery27().equals("企业担保人")){//注册子账号
					String qyid = fxyGzgl02.getQuery19();
					String qiyeuserid = "";
					QueryWrapper<FxyGzgl03> queryWrapper3 = new QueryWrapper<FxyGzgl03>();
					queryWrapper3.eq("query13", qyid);
					queryWrapper3.eq("query07", fxyGzgl02.getQuery07());
					List<FxyGzgl03> list03 = fxyGzgl03Service.list(queryWrapper3);
					qiyeuserid = list03.get(0).getQuery24();
					if (StringUtil.isEmpty(qiyeuserid)){
						FxyGzgl03 fxyGzgl03 =  list03.get(0);

						String fileidfm ="";//上传营业执照
						if( StringUtil.isNotEmpty(fxyGzgl03.getQuery27())
								&&StringUtil.isEmpty(fxyGzgl03.getQuery28())){
							try{
								fileidfm = upload("营业执照",fxyGzgl03.getQuery27(),"1000","1999","");
								fxyGzgl03.setQuery28(fileidfm);

							}catch (Exception e){
							}
						}

						try {
							fxyUser fxyUser3 = new fxyUser();
							fxyUser3.setEnterpriseName(fxyGzgl03.getQuery12());
							fxyUser3.setBusinessLicenseId(fxyGzgl03.getQuery13());
							fxyUser3.setBusinessLicenseFileId(fxyGzgl03.getQuery28());
							fxyUser3.setOrgId(fxyGzgl03.getQuery14());
							fxyUser3.setAddress(fxyGzgl03.getQuery15());
							fxyUser3.setLegalPersonType(fxyGzgl03.getQuery16());
							fxyUser3.setLegalPersonCard(fxyGzgl03.getQuery17());
							fxyUser3.setLegalPersonPhone(fxyGzgl03.getQuery18());
							fxyUser3.setLegalPersonName(fxyGzgl03.getQuery22());

							String res3 = fxyUtil.realnameRegisterEnterpriseUser(appCode, redisUtil, fxyUser3);
							if (!StringUtil.isEmpty(res3)) {
								fxyGzgl03.setQuery24(res3.split("-")[0]);
								fxyGzgl03.setQuery29(res3.split("-")[1]);
								qiyeuserid = fxyGzgl03.getQuery24();
								res = fxyGzgl03.getQuery29();
							}
						} catch (BaseBusinessException e) {
							fxyGzgl03.setQuery38(e.getMessage());
							fxyGzgl03Service.updateById(fxyGzgl03);
							return Result.error(e.getMessage());
						}
						fxyGzgl03Service.updateById(fxyGzgl03);
					}
					if(StringUtil.isNotEmpty(qiyeuserid)){
//						fxyUser.setUserId(qiyeuserid);
//						res = fxyUtil.registerSubUser(appCode,redisUtil,fxyUser);
						fxyGzgl02.setQuery20(res);

					}else{
						return Result.ok("企业注册失败");
					}
				}else{
					res = fxyUtil.realnameRegister(appCode,redisUtil,fxyUser);
				    fxyGzgl02.setQuery20(res);
				}
		}catch (BaseBusinessException e){
                fxyGzgl02.setQuery38(e.getMessage());
                fxyGzgl02Service.updateById(fxyGzgl02);

                return Result.error(e.getMessage());
		}
		}
       String fileidzm ="";
       String fileidfm ="";
		if(StringUtil.isNotEmpty(fxyGzgl02.getQuery20())&&StringUtil.isNotEmpty(fxyGzgl02.getQuery23())&&StringUtil.isEmpty(fxyGzgl02.getQuery24())){
			try{
				fileidzm = upload("身份证正面",fxyGzgl02.getQuery23(),"1000","1001",fxyGzgl02.getQuery20());
				fxyGzgl02.setQuery24(fileidzm);

			}catch (Exception e){
			}
		}
		if(StringUtil.isNotEmpty(fxyGzgl02.getQuery20())&&StringUtil.isNotEmpty(fxyGzgl02.getQuery25())&&StringUtil.isEmpty(fxyGzgl02.getQuery28())){
			try{
				fileidfm = upload("身份证反面",fxyGzgl02.getQuery25(),"1000","1002",fxyGzgl02.getQuery20());
				fxyGzgl02.setQuery28(fileidfm);

			}catch (Exception e){
			}
		}





//		if(StringUtil.isNotEmpty(fxyGzgl02.getQuery20())
//
//				&&StringUtil.isNotEmpty(fxyGzgl02.getQuery24())
//				&&StringUtil.isNotEmpty(fxyGzgl02.getQuery28())
//				&&"已实名".equals(fxyGzgl02.getQuery22())
//		){
			//实名操作
//			try{
//				fxyUser fxyusersm = new fxyUser();
//				fxyusersm.setUserId(fxyGzgl02.getQuery20());
//				fxyusersm.setName(fxyGzgl02.getQuery13());
//				fxyusersm.setIdCode(fxyGzgl02.getQuery15());
//				fxyusersm.setNationalEmblemFileId(fxyGzgl02.getQuery28());
//				fxyusersm.setHumanFaceFileId(fxyGzgl02.getQuery24());
//				fxyUtil.doRealnameByOCR2Element(appcode,redisUtil,fxyusersm);
//			}catch (Exception e){
//
//			}





//		}





//		try{
//			//实名查询
//			fxyUser fxyusersmquery = new fxyUser();
//			fxyusersmquery.setUserId(fxyGzgl02.getQuery20());
//			String realnamesearch = fxyUtil.realnamesearch(appcode,redisUtil,fxyusersmquery);
//			System.out.println("realnamesearch===="+realnamesearch);
//			if(StringUtil.strPos(realnamesearch,"verifyType")){
//				fxyGzgl02.setQuery22("已实名");
//
//			}else{
//				fxyGzgl02.setQuery22("已实名");
//
//			}
//		}catch (Exception e){
//
//		}


//		if(!StringUtil.isEmpty(fxyGzgl02.getQuery20())&&"已实名".equals(fxyGzgl02.getQuery22())){
//			fxyUser fxyUserca = new fxyUser();
//			fxyUserca.setUserId(fxyGzgl02.getQuery20());
//			try{
//				fxyUtil.doRealnameByCA(appCode,redisUtil,fxyUserca);
//			}catch (Exception e){
//
//			}
//		}
		fxyGzgl02Service.updateById(fxyGzgl02);

		return Result.ok("编辑成功!");
	}



	 /**
	  *  编辑
	  *
	  * @return
	  */
	 @PutMapping(value = "/edit22")
	 public Result<?> edit(HttpServletRequest request, HttpServletResponse response ,
						   @RequestParam(name="para", required = false) String para) {
		 FxyGzgl02 fxyGzgl02 = fxyGzgl02Service.getbyquery12(para);
		 fxyGzgl02.setQuery22("已实名");
		 fxyGzgl02Service.updateById(fxyGzgl02);
		 return Result.ok("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		fxyGzgl02Service.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fxyGzgl02Service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FxyGzgl02 fxyGzgl02 = fxyGzgl02Service.getById(id);
		if(fxyGzgl02==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(fxyGzgl02);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fxyGzgl02
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FxyGzgl02 fxyGzgl02) {
        return super.exportXls(request, fxyGzgl02, FxyGzgl02.class, "公证相关人员信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FxyGzgl02.class);
    }

}
